package org.feng.clog;

import lombok.extern.slf4j.Slf4j;
import org.feng.clog.annotation.ProcessorBean;
import org.feng.clog.utils.SpringBeanUtils;

import javax.annotation.PostConstruct;

/**
 * 处理器模板
 *
 * @author feng
 */
@Slf4j
public abstract class AbstractProcessorTemplate<T, R> implements Processor<T, R> {

    protected void init(ProcessorContext<T> context) {
    }

    protected void after(ProcessorContext<T> context, R result) {
    }

    public R start(ProcessorContext<T> context) {
        init(context);

        // 直接调用handle会导致aop失效
        // R result = handle(context);

        AbstractProcessorTemplate<T, R> template = SpringBeanUtils.getByClass(this.getClass());
        R result = template.handle(context);

        after(context, result);

        return result;
    }


    @PostConstruct
    private void registerProcessor() {
        if (this.getClass().isAnnotationPresent(ProcessorBean.class)) {
            ProcessorBean processorBean = this.getClass().getDeclaredAnnotation(ProcessorBean.class);

            log.info("ProcessorBean Register, action is {}, processor is {}", processorBean.action(), this.getClass().getName());
            ProcessorFactory.register(processorBean.action(), this);
        }
    }
}
